﻿using System.IO;
using System.Net;
using System.Text;

namespace ZHDJ.MobileInterface
{
    public sealed class PushHelper
    {
        ///<summary>
        /// 
        /// </summary>
        public static OutParam PushMessage<InParam, OutParam>(string pushUrl, InParam inParam)
            where InParam : class
            where OutParam : class
        {
            HttpWebRequest request = HttpWebRequest.Create(pushUrl) as HttpWebRequest;
            request.Method = "POST";

            request.Timeout = 100 * 1000;    // 执行超时时间为10秒
            request.Credentials = CredentialCache.DefaultCredentials;

            // 序列化请求报文
            string strOriRequestMsg = SerializeHelper.JsonSerializer<InParam>(inParam);

            // 加密请求报文
            //string strEncRequestMsg = CryptoHelper.Encrypt(strOriRequestMsg);
            string strEncRequestMsg = strOriRequestMsg;

            byte[] requestBytes = Encoding.UTF8.GetBytes(strEncRequestMsg);
            request.ContentLength = requestBytes.Length;
            using (Stream writer = request.GetRequestStream())
            { writer.Write(requestBytes, 0, requestBytes.Length); }

            string strOriResponseMsg = string.Empty;
            using (StreamReader reader = new StreamReader(request.GetResponse().GetResponseStream(), Encoding.UTF8))
            { strOriResponseMsg = reader.ReadToEnd(); }

            OutParam outParam = null;
            if (!string.IsNullOrEmpty(strOriResponseMsg))
            {
                // 解密响应报文
                //string strDecResponseMsg = CryptoHelper.Decrypt(strOriResponseMsg);
                string strDecResponseMsg = strOriResponseMsg;

                // 反序列化响应报文
                outParam = SerializeHelper.JsonDeserialize<OutParam>(strDecResponseMsg);
            }

            return outParam;
        }
    }
}